package cn.mujiankeji.mbrowser.界面.标签页.聚搜

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import cn.mujiankeji.mbrowser.功能.浏览框.浏览框视图
import cn.mujiankeji.mbrowser.界面.组件.按钮.水平标签
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collect


@Composable
fun 聚搜页面实现(state: 聚搜页面状态) {

    state.coroutine = rememberCoroutineScope()
    DisposableEffect(Unit) {
        onDispose {
            state.coroutine = null
        }
    }

    LaunchedEffect(state.pagerState.currentPage,state.webviews.size) {
        if (state.pagerState.currentPage < state.webviews.size) {
            state.webviews[state.pagerState.currentPage].标题.collect{
                state.标题.value = it
            }
        }
    }

    Scaffold(containerColor = MaterialTheme.colorScheme.surface) {
        Column(Modifier.padding(top = it.calculateTopPadding())) {
            标签栏视图(state)
            内容视图(state)
        }
    }
}

@Composable
private fun 标签栏视图(state: 聚搜页面状态){
    LazyRow(Modifier.fillMaxWidth()
        .height(50.dp),
        verticalAlignment = Alignment.CenterVertically) {

        itemsIndexed(state.searchEngine.地址列表){index,it->
            if (it.地址.isNotEmpty()){
                水平标签(it.名称.ifEmpty { state.searchEngine.名称 },state.pagerState.currentPage == index,
                    paddingValues = PaddingValues(horizontal = 10.dp)
                ){
                    state.切换标签(index)
                }
            }
        }

    }

}

@Composable
private fun 内容视图(state: 聚搜页面状态){

    HorizontalPager(state = state.pagerState,
        modifier = Modifier.fillMaxSize()) { pageIndex ->
        if (state.webviews.size < pageIndex){
            Box(Modifier.fillMaxSize()) {
                Text("引擎启用失败", modifier = Modifier.align(Alignment.Center))
            }
        }
        else {
            浏览框视图(state.webviews[pageIndex])

        }


    }
}







